package com.talent.web.config.security;

import com.google.gson.Gson;
import com.talent.web.exception.TalentAuthenticationException;
import com.talent.web.model.TalentResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName：TalentAuthenticationEntryPoint
 * @Author: hszhou
 * @Date: 2024/10/21 13:35
 * @Description: 没有登陆就直接访问资源会调用这个类
 */
@Component
public class TalentAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private static final Logger logger = LoggerFactory.getLogger(TalentAuthenticationEntryPoint.class);
    @Autowired
    private Gson gson;
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        //用户名或密码错误
        logger.error("未登录【{}】",authException.getMessage());
        TalentResult<Object> result =null;
        if(authException instanceof TalentAuthenticationException) {
            TalentAuthenticationException ex = (TalentAuthenticationException) authException;
            result = TalentResult.error(ex.getResponse());
        }else{
            result=TalentResult.error(authException.getMessage());
        }
        String json = gson.toJson(result);
        writer.println(json);
    }
}
